using Godot;
using System;

public partial class CameraController : Node2D
{

  private float _zoomLevel = 1;
  private bool _isDrag = false;

  private Camera2D _camera;

  private Vector2 _oldPos;

  private Vector2 _mousePos;
  private Vector2 _mouseScreenPos;
  private Vector2 _mouseScreenOldPos;

  public override void _Ready()
  {
    _camera = GetNode<Camera2D>("/root/BigMap/Camera2D");
    _zoomLevel = _camera.Zoom.X;
  }


  public override void _Process(double delta)
  {
    if (_isDrag)
    {
      _camera.Position = _oldPos - (_mouseScreenPos - _mouseScreenOldPos) * _zoomLevel;
    }
  }

  public override void _UnhandledInput(InputEvent @event)
  {
    if (BigMap.IsUIActive) return;
    if (@event is InputEventMouse m)
    {
      _mousePos = GetGlobalMousePosition();
      _mouseScreenPos = m.Position;

      if (m is InputEventMouseButton mb)        //  鼠标按键
      {
        switch (mb.ButtonIndex)
        {
          case MouseButton.WheelUp:     //  滚轮向后缩小
            if (mb.Pressed && _zoomLevel < 2.5)
            {
              _zoomLevel += 0.1f;
              Zoom(_zoomLevel);
            }
            break;

          case MouseButton.WheelDown:       //  向前放大
            if (mb.Pressed && _zoomLevel > 0.6)
            {
              _zoomLevel -= 0.1f;
              Zoom(_zoomLevel);
            }
            break;

          case MouseButton.Left:
            if (mb.Pressed)
            {
              _isDrag = true;
              _mouseScreenOldPos = _mouseScreenPos;
              _oldPos = _camera.Position;
            }
            else { _isDrag = false; }
            break;
        }
      }
    }
  }

  void Zoom(float zoom_)
  {
    _camera.Zoom = new Vector2(zoom_, zoom_);
    _camera.Position += -(GetGlobalMousePosition() - _mousePos);     //  每次微小滚动造成的偏差都对齐回来
    _camera.ForceUpdateScroll();     //  马上更新
  }
}
